package com.jianggujin.demo.admin.handler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.jianggujin.modulelink.config.JModuleConfig;
import com.jianggujin.modulelink.config.JMultiVersionModuleConfig;
import com.jianggujin.modulelink.magager.JModuleManager;
import com.jianggujin.modulelink.module.JModule;
import com.jianggujin.modulelink.module.JModuleState;

import fi.iki.elonen.NanoHTTPD.IHTTPSession;
import lombok.Data;

public class ListHandler extends AbstractHandler {

    @Override
    protected Object handle(JModuleManager manager, IHTTPSession session, Map<String, String> params) throws Exception {
        List<ModuleItem> moduleItems = new ArrayList<ModuleItem>();
        for (JModule<JModuleConfig> module : manager.getModules()) {
            JModuleConfig config = module.getModuleConfig();
            ModuleItem item = new ModuleItem();
            item.setModuleName(config.getModuleName());
            item.setActived(JModuleState.ACTIVED == module.getModuleState());
            item.setDescription(config.getDescription());
            if (config instanceof JMultiVersionModuleConfig) {
                item.setVersion(((JMultiVersionModuleConfig) config).getVersion());
            }
            item.setActionNames(module.getActionNames());
            moduleItems.add(item);
        }
        Collections.sort(moduleItems, new Comparator<ModuleItem>() {

            @Override
            public int compare(ModuleItem o1, ModuleItem o2) {
                int value = o1.getModuleName().compareTo(o2.getModuleName());
                return value != 0 ? value : o1.getVersion().compareTo(o2.getVersion());
            }
        });
        return success(moduleItems);
    }

    @Data
    public static class ModuleItem {
        private String moduleName;
        private boolean actived;
        private String description;
        private String version;
        private Set<String> actionNames;
    }
}
